// 显示消息提示框 icon 图标, msg提示文字
function Toast(msg, icon = '') {
  return uni.showToast({
    title: msg,
    icon: icon ? icon : 'none'
  })
}

function Back() {
  uni.navigateBack()
}

/**
 * 路由跳转
 * @param {String} url - 跳转路径
 * @return {String}  type - 跳转的类型
 */
function jump(url, type) {
  switch (type) {
    case 'navigate': //保留当前页面，跳转到应用内的某个页面
      uni.navigateTo({
        url: url,
      });
      break;
    case 'redirect': //关闭当前页面, 跳转到应用内的某个页面
      uni.redirectTo({
        url: url
      });
      break;
    case 'reLaunch': //关闭所有页面, 打开到应用内的某个页面
      uni.reLaunch({
        url: url
      });
      break;
    case 'switch': //跳转到tabbar页面
      uni.switchTab({
        url: url
      });
      break;
    case 'web':
      uni.navigateTo({ //跳转外部链接
        url: '/pages/web/index?link=' + encodeURIComponent(JSON.stringify(url))
      });
      break;
    case 'navigateBack':
      uni.navigateBack({
        delta: url // 1 || 2 
      })
    default: //默认方法
      uni.navigateTo({
        url: url
      });
      break;
  }
}


function getCurrentTime(data) {
  let Y = data.getFullYear(),
    M = data.getMonth() + 1,
    D = data.getDate(),
    h = data.getHours(),
    m = data.getMinutes(),
    s = data.getSeconds();

  function fromData(time) {
    return time > 9 ? time : `0${time}`
  }
  return [fromData(Y), fromData(M), fromData(D), fromData(h), fromData(m), fromData(s)]
}
// 时间格式化
function formatTime(time, type = 'Y-M-D h:m:s') {
	 let getTime
	if(time==0){
		getTime = getCurrentTime(new Date())
	}else{
		getTime = getCurrentTime(new Date(time * 1000))
	}
 
  if (type == 'Y-M-D h:m:s') {
    return `${getTime[0]}-${getTime[1]}-${getTime[2]} ${getTime[3]}:${getTime[4]}:${getTime[5]}`
  } else if (type == 'Y-M-D') {
    return `${getTime[0]}-${getTime[1]}-${getTime[2]}`
  } else if (type == 'Y/M/D h:m:s') {
    return `${getTime[0]}/${getTime[1]}/${getTime[2]}`
  } else if (type == 'Y/M/D') {
    return `${getTime[0]}/${getTime[1]}/${getTime[2]}`
  }
}

// 简单防抖 频繁切换页面时的请求
const debounceType = (function() {
  var oldType
  return (type, fun) => {
    if (type < 0) return
    if (type === oldType) return
    oldType = type
    fun()
  }
})()

// 防抖函数
let debounce = (function() {
  let timer;
  return function(func, wait) {
    let context = this
    let args = arguments
    if (timer) clearTimeout(timer)
    let callNow = !timer
    timer = setTimeout(() => {
      timer = null
    }, wait)
    if (callNow) func.apply(context, args)
  }
})();
// 处理苹果手机的时间兼容问题
let timeStr = (str) => {
  return str.replace(/\-/g, "/")
}
//把时间 /换成 -
let returnTimeStr = (str) => {
  return str.replace(/\//g, "-")
}

// 延迟时间
const setTime = 1000

// 手机号转换****
function geTel(tel){
    return tel.substring(0, 3)+"****"+tel.substr(tel.length-4);
}

// 银行卡保留后四位
function getBankLast(number){
	return "****"+number.substr(number.length-4);
}

// 名字转换****
function getName(name){
	if(!name) return
    var newStr;
	if (name.length === 2) {
		newStr = name.substr(0, 1) + '*';
	} else if (name.length > 2) {
		var char = '';
		for (var i = 0, len = name.length - 2; i < len; i++) {
			char += '*';
		}
		newStr = name.substr(0, 1) + char + name.substr(-1, 1);
	} else {
		newStr = name;
	}
	return newStr;
}

//身份证号换成*
function geIdNumber(idcard){
	return idcard.substring(0, 3)+"***************"+idcard.substr(idcard.length-4);
    // return idcard.replace(/(\w{2})\w*(\w{2})/, '$1**************$2');
}

 // 获取距离时间
 function getDistance(date,type=1)
 {
	 date = timeStr(date)
 	 var time1 = new Date()
 	 var time2 = new Date(date)
	 
	
 	 var diffTime = Math.round(Math.abs(time1.getTime() - time2.getTime()) / 1000)
 	 var day = parseInt(diffTime/60/60/24);
 	 var hour = parseInt(diffTime/60/60%24);
 	 var min = parseInt(diffTime/60%60);
 	 var sen = parseInt(diffTime%60);
 	 
	 if(type==2){
		  let bool = false
		  
		  // 转换为日期对象
		  let dd = new Date();
		  // 格式化日期为 "yyyy-MM-dd" 的字符串并存入数组
		  let year = dd.getFullYear();
		  let month = ("0" + (dd.getMonth() + 1)).slice(-2);
		  let day = ("0" + dd.getDate()).slice(-2);
		  let now = year + "/" + month + "/" + day
		  let _update = date.split(' ')[0]
		
		  if(now==_update){
			 bool = true
		  }
		  return bool
	 }else{
		 if(day>0){
		 		 return day+'天'
		 }else if(hour>0){
		 		 return hour+'小时'
		 }else{
		 		 return min+'分钟'
		 }
	 }
	 
 	 
 	
 }
 
 // 获取近num天日期
 function getDates(num=7)
 {
	 // 创建一个空数组来存储日期
	 let dates = [];
	 
	 // 获取当前日期
	 let now = new Date();
	 
	 // 循环获取最近 num 天的日期
	 for (let i = 0; i < num; i++) {
	   // 获取当前日期的时间戳
	   let timestamp = now.getTime();
	 
	   // 计算 i 天前的时间戳
	   let dayTimestamp = 24 * 60 * 60 * 1000; // 一天的毫秒数
	   let iDayAgoTimestamp = timestamp - i * dayTimestamp;
	 
	   // 转换为日期对象
	   let date = new Date(iDayAgoTimestamp);
	 
	   // 格式化日期为 "yyyy-MM-dd" 的字符串并存入数组
	   let year = date.getFullYear();
	   let month = ("0" + (date.getMonth() + 1)).slice(-2);
	   let day = ("0" + date.getDate()).slice(-2);
	   dates.push(year + "-" + month + "-" + day);
	 }
	 return dates
 }
 
 //截取字符串
 function sliceStr(str,num=1){
 
       var len = str.length - 5
       str = str.slice(len-num,len)
 
       return str
 
 }
 
 // 时间转换
 function getDateDiff(dateTimeStamp) {
	     
         var minute = 1000 * 60;
         var hour = minute * 60;
         var day = hour * 24;
         var halfamonth = day * 15;
         var month = day * 30;
  
         var now = new Date().getTime();
		 dateTimeStamp = new Date(dateTimeStamp).getTime();
         var diffValue = now - dateTimeStamp;
         if (diffValue < 0) {
             //若日期不符则弹出窗口告之
             //alert("结束日期不能小于开始日期！");
         }
         var monthC = diffValue / month;
         var weekC = diffValue / (7 * day);
         var dayC = diffValue / day;
         var hourC = diffValue / hour;
         var minC = diffValue / minute;
		 let result
         if (monthC >= 1) {
             result =  parseInt(monthC) + "个月前";
         } else if (weekC >= 1) {
             result =  parseInt(weekC) + "周前";
         } else if (dayC >= 1) {
             result =  parseInt(dayC) + "天前";
         } else if (hourC >= 1) {
             result =  + parseInt(hourC) + "个小时前";
         } else if (minC >= 1) {
             result =  + parseInt(minC) + "分钟前";
         } else
             result = "刚刚";
         return result;
}

// 数组去重
function unique(arr,key){
        for(var i=0; i<arr.length; i++){
            for(var j=i+1; j<arr.length; j++){
                if(arr[i][key]==arr[j][key]){         //第一个等同于第二个，splice方法删除第二个
                    arr.splice(j,1);
                    j--;
                }
            }
        }
    return arr;
}

// 特殊去重

 function specialunique(arr,key,key2){
         for(var i=0; i<arr.length; i++){
             for(var j=i+1; j<arr.length; j++){
                 if(arr[i][key]==arr[j][key] && arr[i][key2]==arr[j][key2]){         //第一个等同于第二个，splice方法删除第二个
                     arr.splice(j,1);
                     j--;
                 }
             }
         }
     return arr;
 }
 
 // 两个数组去重返回新数组
 
 function uniqueArr(arr1,arr2){
	 let arr = []
	 for(let item of arr1){
		 let index = arr2.findIndex(el=>{
			 return item==el
		 })
		 if(index==-1){
			 arr.push(item)
		 }
	 }
	 return arr
 }

//  两个数组返回数组1中的值是否在数组2中存在
// 0不存在 1存在
 function isEmpotyArr(arr1,arr2){
	 let arr = []
	 for(let item of arr1){
		 let index = arr2.findIndex(el=>{
			 return item==el
		 })
		 if(index==-1){
			 return 0
		 }else{
			 return item
		 }
	 }
	 
 }
 
 // 获取当前时间
 function  formatNowDate(type=1) {
   let date = new Date();
   let Y = date.getFullYear()
   let M = date.getMonth() + 1
   let D = date.getDate()
   let h = date.getHours()
   let m = date.getMinutes()
   let s = date.getSeconds()
   function Time(time) {
     return time > 9 ? time : '0' + time
   }
   if(type==1){
 	  return `${Y}-${Time(M)}-${Time(D)} ${Time(h)}:${Time(m)}:${Time(s)}`
   }else{
 	  return `${Y}-${Time(M)}-${Time(D)}`
   }
 }
 
 // 生成订单编号
 function createOrderSn(length=4) {
	let str = new Date().getTime() + Math.random().toString(9).substring(2, length + 2);
   // let str = new Date().getTime() + Math.random().toString(36).substring(2, length + 2);
   return revlesOrderSn(str);
 }
 
 // 订单编号转换为年月日时分秒
 function revlesOrderSn(str) {
	 let date = str.substring(0,13)*1
	     date = new Date(date)
	 let Y = date.getFullYear()
	 let M = date.getMonth() + 1
	 let D = date.getDate()
	 let h = date.getHours()
	 let m = date.getMinutes()
	 let s = date.getSeconds()
	 function Time(time) {
	   return time > 9 ? time : '0' + time
	 }
	 let lastStr = str.substr(-4)
	 return `${Y}${Time(M)}${Time(D)}${Time(h)}${Time(m)}${Time(s)}${lastStr}`
 }
 
 // 数组分成两个
 function splitArray(arr) {
     let middle = Math.ceil(arr.length / 2),
         firstHalf = arr.slice(0, middle),
         secondHalf = arr.slice(middle);
     return [firstHalf, secondHalf];
 }
 
 
 // 获取时间差
 function countdown(creat_time,shift_time,type=1){
 	const now = new Date().getTime();
 	const endTime = new Date(creat_time).getTime() + (shift_time*60*1000)
 	const distance = endTime - now;
	
 	if (distance < 0) {
		if(type==1){
			return `0天0时0分`
		}else{
			return [0,0,0]
		}
 		
 	}
 	
	const days = Math.floor(distance / (1000 * 60 * 60 * 24));
	const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    
	
	if(type==1){
		return `${days}天${hours}时${minutes}分`
	}else{
		return [days,hours,minutes]
	}
 
 }

export default {
	countdown,
	revlesOrderSn,
	createOrderSn,
	getBankLast,
	splitArray,
  formatNowDate,
  isEmpotyArr,
  uniqueArr,
  specialunique,
  unique,
  getDateDiff,
  sliceStr,
  geIdNumber,
  getName,
  getDates,
  getDistance,
  geTel,
  Toast,
  setTimeout: setTime,
  Back,
  jump,
  debounceType,
  debounce,
  formatTime,
  timeStr,
  returnTimeStr
}
